using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Models;
using MQTTnet.Client;
using NLog;
using System.Globalization;
using System.Windows;
using ViewModels;
using WorkPieceDataCapture.Views;
using System.Threading;
using WorkPieceDataCapture.ViewModels;
using Services;

namespace WorkPieceDataCapture
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private static Mutex _mutex = null;
        ServiceProvider serviceProvider;
        public App()
        {
            
        }
        protected override void OnStartup(StartupEventArgs e)
        {
            const string appName = "WorkPieceDataCapture";
            bool createdNew;

            _mutex = new Mutex(true, appName, out createdNew);

            if (!createdNew)
            {
                MessageBox.Show("应用程序已经在运行中！", "警告", MessageBoxButton.OK, MessageBoxImage.Warning);
                Current.Shutdown();
                return;
            }

            base.OnStartup(e);
            var services = new ServiceCollection();
            ConfigureServices(services);
            serviceProvider = services.BuildServiceProvider();

            var mainWindowViewModel = serviceProvider.GetService<vm_MainWindow>();
            var mainWindow = new MainWindow { DataContext = mainWindowViewModel };
            mainWindow.Show();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);

            if (_mutex != null)
            {
                _mutex.ReleaseMutex();
                _mutex.Dispose();
            }
        }

        private void ConfigureServices(ServiceCollection services)
        {
            // 配置数据库连接字符串
            var connectionString = "DefaultConnection"; // 可以从配置文件中读取
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json");
            var configuration = builder.Build();
            // 将 IConfiguration 注入容器，供各处（例如 vm_MainWindow）按需使用
            services.AddSingleton<IConfiguration>(configuration);
            var dbConnectionString = configuration.GetConnectionString(connectionString);
            GlobalClass.WindowWidth = int.Parse(configuration["ScreenWidth"].ToString());
            GlobalClass.WindowHeight = int.Parse(configuration["ScreenHeight"].ToString());
            var serverVersion = ServerVersion.Parse("8.0.21");
            services.AddDbContext<AppDbContext>(options =>
                options.UseMySql(dbConnectionString, serverVersion), ServiceLifetime.Transient);
            //配置MQTT
            services.AddScoped(obj => new Model_MQTTLoginInfo()
            {
                strIPAddress = configuration.GetSection("MQTT_Connection").GetSection("IPAddress").Value,
                intPort = int.Parse(configuration.GetSection("MQTT_Connection").GetSection("Port").Value),
                strClientID = configuration.GetSection("MQTT_Connection").GetSection("ClientID").Value,
                strLoginUserName = configuration.GetSection("MQTT_Connection").GetSection("UserName").Value,
                strLoginPassword = configuration.GetSection("MQTT_Connection").GetSection("Password").Value,
                strEquipSubscribeTopic = configuration.GetSection("MQTT_Connection").GetSection("EquipSubscribeTopic").Value,
                strCubeSubscribeTopic = configuration.GetSection("MQTT_Connection").GetSection("CubeSubscribeTopic").Value,
            });
            services.AddSingleton<Logger>();
            services.AddScoped<MQTT_Client>();

            //配置TCP监听器
            var tcpPort = int.Parse(configuration.GetSection("TcpListener").GetSection("Port").Value ?? "8888");
            services.AddSingleton(provider => new TcpDataListener(tcpPort));

            // 其他服务配置...
            services.AddTransient<vm_MainWindow>();     //主界面的ViewModel
            services.AddTransient<vm_WorkPieceDatacapture_RealTime>();      //实时生产数据采集界面的ViewModel
            services.AddTransient<vm_WorkPieceDatacapture_Search>();        //历史数据查询界面的ViewModel
            services.AddTransient<vm_Search_PointCheck>();        //点检记录历史数据查询界面的ViewModel
            services.AddTransient<vm_Chart_NG>();        //NG统计饼图查询界面的ViewModel
            services.AddTransient<vm_Chart_Range>();        //NG统计饼图查询界面的ViewModel
            services.AddTransient<vm_Chart_Coordinate>();   //坐标曲线图界面的ViewModel

        }
    }
}
